package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements IWechatService {


@Value("${wechat.appid}")
private String appid;
@Value("${wechat.appsecret}")
private String appsecret;


private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";


//获取openid方法
@Override
public String getOpenid(String code) {

    Map<String,Object> params = new HashMap<>();
    params.put("appid",appid);
    params.put("secret",appsecret);
    params.put("js_code",code);
    params.put("grant_type","authorization_code");


    HttpResponse response = HttpUtil.createRequest(Method.GET, OPENID_URL)
            .form(params)
            .execute();

    if (response.isOk()) {
        String body = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        return jsonObject.getStr("openid");
    }
    return null;
}

//获取手机号方法
@Override
public String getPhone(String phoneCode) {

    Map<String,Object> params = new HashMap<>();
    params.put("code",phoneCode);


    HttpResponse response = HttpUtil.createRequest(Method.POST, PHONE_URL+getToken())
            .body(JSONUtil.toJsonStr(params))
            .execute();

    if (response.isOk()) {
        String body = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String phoneNumber = jsonObject.getByPath("phone_info.phoneNumber",String.class);

        return phoneNumber;
    }
    return null;


}

private String getToken() {

    Map<String,Object> params = new HashMap<>();
    params.put("appid",appid);
    params.put("secret",appsecret);
    params.put("grant_type","client_credential");


    HttpResponse response = HttpUtil.createRequest(Method.GET, TOKEN_URL)
            .form(params)
            .execute();

    if (response.isOk()) {
        String body = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        return jsonObject.getStr("access_token");
    }
    return null;

}
}